/**
 * 
 */
package com.miolr.module.core.config;

import javax.inject.Inject;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.support.ConnectionFactoryRegistry;

import com.couponornot.social.weibo.connect.v2.WeiboConnectionFactory;
import com.miolr.module.core.service.SocialConnectionService;
import com.miolr.module.core.social.SocialUserConnectionRepository;

/**
 * @author iday
 * 
 */
@Configuration
@ComponentScan({ "com.miolr.module.core.api" })
@PropertySource("classpath:/social.properties")
public class SocialConfig {

	@Inject
	Environment env;
	@Inject
	SocialConnectionService connectionService;

	@Bean
	@Scope("request")
	public ConnectionRepository connectionRepository() {
		return new SocialUserConnectionRepository(connectionService,
				"#{request.userPrincipal.name}", connectionFactoryLocator(),
				textEncryptor());
	}

	@Bean
	public ConnectionFactoryRegistry connectionFactoryLocator() {
		ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
		registry.addConnectionFactory(weiboConnectionFactory());
		return registry;
	}

	@Bean
	public ConnectionFactory<?> weiboConnectionFactory() {
		ConnectionFactory<?> connectionFactory = new WeiboConnectionFactory(
				env.getProperty("weibo.clientId"),
				env.getProperty("weibo.clientSecret"));
		return connectionFactory;
	}
	
	@Bean
	public TextEncryptor textEncryptor() {
		return Encryptors.noOpText();
	}
}
